//
//  ZHLEEStatusPhotos.swift
//  ZHLEE_Blog_Swift_Pro
//
//  Created by ZHLEEBlander on 15/10/20.
//  Copyright © 2015年 ZHLEEBlander. All rights reserved.
//

import UIKit

///最大图片数
private let Max_Count = 9

private let Photo_Magin: CGFloat = 10

class ZHLEEStatusPhotos: UIView {

    var pic_urls: [ZHLEEStatusPhotoInfo]? {
    
        didSet{
        
            setPicUrl()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        for _ in 0..<9 {
        
            let imageView = ZHLEEStatusPhotoImageView(frame: CGRectZero)
            
            addSubview(imageView)
            
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        if pic_urls == nil{
        
            return
        }
        
        let maxCol = 3
        
//        每一张图片的宽高
        let childViewWH = (ScreenW - 4 * Photo_Magin) / CGFloat(maxCol)
        
        //如果是4张图片 选择两张
        let tempCol = pic_urls!.count == 4 ? 2 : maxCol
        
        for i in 0..<pic_urls!.count {
        
            let childView = subviews[i]
            
            let col = i % tempCol
            
            let row = i / tempCol
            
            let childViewX = CGFloat(col) * (childViewWH + Photo_Magin)
            let childViewY = CGFloat(row) * (childViewWH + Photo_Magin)
            //设置每张图片的frame
            childView.frame = CGRect(x: childViewX, y: childViewY, width: childViewWH, height: childViewWH)
        }
    }
    
    private func setPicUrl(){
    
        //首先,让所有的子View隐藏
        for childView in subviews {
            childView.hidden = true
        }
        //根据数据来显示多少个子view
        for i in 0..<pic_urls!.count {
        
            let childView = subviews[i] as! ZHLEEStatusPhotoImageView
            
            childView.hidden = false
            
            let picinfo = pic_urls![i]
            
            //设置图片
            childView.thumbnail_pic = picinfo.thumbnail_pic!
        }
    }
    
    /**
    *  根据图片个数,算出一共的size
    */
    class func size(count: Int)->CGSize {
        //最大列数
        let maxCol = 3
        
        //如果 count = 2 -> 0 count = 3 ->1
        let row = (count - 1) / maxCol + 1
        
        //每个子空件view的高宽
        let childViewWH = (ScreenW - 4 * Photo_Magin) / CGFloat(maxCol)
        
        //计算高宽
        let viewW = ScreenW - 2 * Photo_Magin
        let viewH = childViewWH * CGFloat(row) + CGFloat(row - 1) * Photo_Magin
        
        return CGSizeMake(viewW, viewH)
    }

}
